﻿
using System;
namespace IntelHexParser
{
	/// <summary>
	/// Represents a single line or record in a Hex File.  Only used if FullParsing is turned on when calling the Parse method.
	/// </summary>
	public class HexRecord
	{
		private byte[] data = null;


		/// <summary>
		/// Gets or Sets the size of the Data array used to store the raw data from the hex record.  
		/// NOTE: Setting this value will create a new Data byte array erasing whatever may have been in memory.
		/// </summary>
		public byte DataSize
		{
			get
			{
				return (byte)this.data.Length;
			}
			set
			{
				this.data = new byte[value];
			}
		}


		/// <summary>
		/// Address for this record.  Stored as read from file with no modification of byte order.
		/// </summary>
		public byte[] Address { get; set; }


		/// <summary>
		/// The type of record.
		/// </summary>
		public RecordTypes RecordType { get; set; }


		/// <summary>
		/// The raw byte array from the hex record line
		/// </summary>
		public byte[] Data
		{
			get
			{
				return this.data;
			}
		}


		/// <summary>
		/// The checksum byte from the hex record
		/// </summary>
		public byte Checksum { get; set; }


		/// <summary>
		/// Returns a HexRecord based on the line passed in.
		/// </summary>
		/// <param name="dataLine">Line from the hex file.</param>
		public HexRecord(string dataLine)
		{
			string line = dataLine;
			if (line.StartsWith(":"))
			{
				line = line.Remove(0, 1);
			}

			//get size from first byte
			this.DataSize = Convert.ToByte(line.Substring(0, 2), 16);
			this.RecordType = (RecordTypes)Enum.Parse(typeof(RecordTypes), line.Substring(6, 2));

			this.Address = new byte[2] { Convert.ToByte(line.Substring(2, 2), 16), Convert.ToByte(line.Substring(4, 2), 16) };
			this.Checksum = Convert.ToByte(line.Substring(line.Length - 2, 2), 16);

			//read in data now
			for (int i = 0; i < line.Length - 10; i += 2)
			{
				//add this byte to our checksum
				byte data = Convert.ToByte(line.Substring(i + 8, 2), 16);

				this.Data[i] = data;
			}
		}
	}
}
